import { VmErr } from "../svm/VmErr";
import { DataBus } from "../utils/DataBus";
import { BaseNode } from "./com/BaseNode";

export class ExecuteFunctionNode extends BaseNode {
    public value: string = ''
    constructor(name?: string) {
        super(name ? name : 'ExecuteFunction');
        this.type = 'ExecuteFunction'
        this.bgColor = '#673ab7'
        this.addAttribute({
            name: "functionName",
            value: this.value || 'none',
            type: 'string',
            disable: true
        })
        this.addInput({ key: 'line' })
        this.addOutput({ key: 'output' })
        this.onAttributeClick = this.onAttributeClickHandler.bind(this)
        this.refresh()
    }
    addAttribute(attr: NodeAttribute): void {
        super.addAttribute(attr)
        if (attr.name === 'functionName' && attr.value !== '') {
            setTimeout(() => {
                this.setArgs({
                    nodeId: attr.value,
                    title: attr.name
                })
            }, 1500)
        }
    }
    onAttributeClickHandler(attr: NodeAttribute) {
        if (attr.name !== 'functionName') {
            return
        }
        DataBus.nodesSelector.show((node => {
            attr.value = node.nodeId
            this.createAttributes()
            DataBus.nodesSelector.hide()
            this.setArgs(node)
        }), node => node.type === 'Function', this)
    }

    private setArgs(node: SelectBtnInfo) {
        const funcNode = DataBus.allNodes.find(n => n.id == node.nodeId)
        if (!funcNode) {
            console.log('function undefined')
            return
        }
        const args = funcNode.getAttribute('argsNumber')
        if (!args) {
            funcNode.setNodeErr()
            console.log('function args error')
            return
        }
        const count = parseInt(args.value)
        if (!count) {
            funcNode.setNodeErr()
            console.log('args:', count)
            return
        }
        this.inputs = this.inputs.filter(input => input.key.includes('line'))
        for (let i = 0; i < count; i++) {
            this.addInput({ key: `arg_${i + 1}` })
        }
        this.refresh()
    }

    verify(): boolean {
        const fun = this.getAttribute('functionName')
        if (fun && fun.value.trim() !== 'none') {
            return true
        }

        throw new VmErr(this.id, `${this.titleContent} args undefined`)
    }
}